package com.menguer.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.poi.ss.usermodel.Workbook;

/**
 * @author menguer@126.com
 * @date 2019年3月9日 下午12:51:10
 * @version 1.0.0
 * @description
 */
public class ResourcesUtil {
	/** Don't let anyone instantiate this class */
	private ResourcesUtil() {
	}

	public final static String A_PATTERN = "<a.*?href=(.*?)[^>]*?>";
	public final static String IMG_PATTERN = "<img.*?src=(.*?)[^>]*?>";
	public final static String LINK_PATTERN = "<link.*?href=\"?(.*?)(\"|>|\\s+)[^>]*?>";
	public final static String SCRIPT_PATTERN = "<script.*?src=\"?(.*?)(\"|>|\\s+)[^>]*?>";
	private static int ch;

	private static String homePage;// 网站主页地址
	private static String code;// 网页源码字符串
	private static String property;// 元素便签中的属性

	private final static String ACTRESSS_IMAGE_URL = "";
	private final static String RELEASE_PATH = System.getProperty("user.dir") + "//WebRoot//documents//release.xlsx";

	public static void getImageByActressName(String actressName) {
		List<String> actressList = listCellByName("actress", actressName);
		// String eName = actressList.get(0);
		String cName = actressList.get(1);
		String url = actressList.get(2);

		String folderName = "D://audiovisual//video//actress//" + cName + "//";
		int b = ACTRESSS_IMAGE_URL.length();
		List<String> list = listElements(url, IMG_PATTERN);
		int count = 0;
		for (int i = 0; i < list.size(); i++) {
			String actress = list.get(i);
			if (actress.indexOf("/vv/") != -1) {
				String imageUrl = getSubstring(actress, "data-original=", "\"").replace("showimg.asp?file=/", "")
						.replace("pic", "img");
				int end = imageUrl.indexOf(".jpg");
				int begin = imageUrl.indexOf("/", b) + 1;
				String imageName = imageUrl.substring(begin, end) + ".jpg";
				count++;
				downloadImage(imageUrl, folderName, imageName);
				System.out.println(imageUrl + "=========" + imageName);
			}
		}
		System.out.println("一共有：" + count + "条数据。");
	}

	public static void downloadImage(String path) {
		// 如果path是图片下载地址，那么直接下载；如果path是网站地址，那么进行筛选，下载其中的图片
		String postfix = ".jpg";
		if (theIsAbsolutePath(path, postfix)) {
			downloadImage(path, getName(path, postfix));
		} else {
			List<String> list = listHttpByTagName(path, "img");
			int cound = 0;
			for (int i = 0; i < list.size(); i++) {
				String name = getName(list.get(i), postfix);
				downloadImage(list.get(i), name);
				cound++;
				System.out.println("name====" + name);
			}
			System.out.println("本次一共下载了" + cound + "张图片！");
		}
	}

	public static void downloadImage(String path, String fileName) {
		String folderName = "D://Picture//image//";
		downloadImage(path, folderName, fileName);
	}

	public synchronized static void downloadImage(String path, String folderName, String fileName) {
		// 后期可以根据传进来的文件类型，选择不同的存放文件夹
		try {
			// 开启输入流
			InputStream in = new URL(path).openStream();
			// 1kb的缓存
			byte by[] = new byte[1024];
			int length;
			createFolder(folderName);
			if (fileName.indexOf(".jpg") == -1) {
				fileName = fileName + ".jpg";
			}
			File file = createFile(folderName + fileName);
			// 开启文件输出流，其实就是向新建的文件写入数据
			FileOutputStream fileOut = new FileOutputStream(file);
			while ((length = in.read(by)) != -1) {
				fileOut.write(by, 0, length);
			}
			in.close();
			fileOut.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取url中符合标签名特征的对象，截取其中的链接地址
	 * 
	 * @param url
	 * @param tagName
	 *            标签名
	 * @return
	 */
	public static List<String> listHttpByTagName(String url, String tagName) {
		return listUrl(listElementsByTagName(url, tagName));
	}

	/**
	 * 通过演员的名字，获取目标文件中对应的演员地址
	 * 
	 * @param path
	 * @param actressName
	 *            演员名字，不论是中文还是英文的
	 * @return
	 */
	public static List<String> listCellByName(String sheetName, String actressName) {
		List<String> list = new ArrayList<String>();
		Workbook workbook = DocumentUtil.readWorkbook(RELEASE_PATH);
		org.apache.poi.ss.usermodel.Sheet sheet = null;
		org.apache.poi.ss.usermodel.Row row = null;

		// 获取每个sheet
		for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
			sheet = workbook.getSheetAt(i);
			if ("actress".equals(sheetName)) {
				// 获取每行
				for (int j = 0; j < sheet.getPhysicalNumberOfRows(); j++) {
					row = sheet.getRow(j);
					// 获取每个单元格
					for (int k = 0; k < row.getPhysicalNumberOfCells(); k++) {
						if (row.getCell(k).toString().equals(actressName)) {
							for (int m = 0; m < row.getPhysicalNumberOfCells(); m++) {
								list.add(row.getCell(m).toString());
							}
						}
					}
				}
			}
		}
		return list;
	}

	/**
	 * 获取网页中具有该标签的元素
	 * 
	 * @param url
	 * @param tagName
	 * @return
	 */
	public static List<String> listElementsByTagName(String url, String tagName) {
		List<String> list = new ArrayList<String>();
		tagName = tagName.toLowerCase();
		if ("a".equals(tagName)) {
			property = "href=";
			list = listElements(url, A_PATTERN);
		} else if ("img".equals(tagName)) {
			property = "src=";
			list = listElements(url, IMG_PATTERN);
		} else if ("link".equals(tagName)) {
			property = "href=";
			list = listElements(url, LINK_PATTERN);
		} else if ("script".equals(tagName)) {
			property = "src=";
			list = listElements(url, SCRIPT_PATTERN);
		} else {
			System.out.println("请输入合法的标签名称！");
		}
		return list;
	}

	/**
	 * 根据regex获取相应的Matcher对象集合，对其遍历得到其中相应的字符串
	 * 
	 * @param url
	 * @param pattern
	 * @return
	 */
	public static List<String> listElements(String url, String regex) {
		List<String> list = new ArrayList<String>();
		if (code == null) {
			code = getCodeByUrl(url);
		}
		try {
			// 简化了这一段Pattern pattern = Pattern.compile(regex,2);
			Matcher matcher = Pattern.compile(regex, 2).matcher(code);
			while (matcher.find()) {
				int start = matcher.start();
				int end = matcher.end();
				String match = code.substring(start, end);
				list.add(match);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	/**
	 * 通过url和后缀名生成文件名称
	 * 
	 * @param url
	 * @param postfix
	 *            后缀名
	 * @return
	 */
	public static String getName(String url, String postfix) {
		String name = getSubstring(url, ":/", postfix);
		name = name.replace(".", "").replace("/", "_").replace("?", "") + postfix;
		return name;
	}

	/**
	 * 通过regex获取想要的字符串集合，根据属性名截取字符串中的url
	 * 
	 * @param url
	 * @param regex
	 * @param property
	 *            属性
	 * @return
	 */
	public static List<String> listUrl(String url, String regex, String property) {
		return listUrl(listElements(url, regex));
	}

	public static List<String> listUrl(List<String> elementsList) {
		List<String> list = new ArrayList<String>();
		for (int i = 0; i < elementsList.size(); i++) {
			String element = elementsList.get(i);
			String http = getSubstring(element, property, "\"");
			if (http.indexOf(":void(0)") == -1 && http.indexOf("://") == -1) {
				http = homePage + http.replace("../", "");
				list.add(http);
			} else if (http.indexOf("://") != -1) {
				list.add(http);
			}
		}
		return list;
	}

	/**
	 * 
	 * @param string
	 *            需要截取的字符串
	 * @param begin
	 *            截取的起始字符串
	 * @param end
	 *            截取的结束字符串
	 * @return
	 */

	public static String getSubstring(String string, String begin) {
		return getSubstring(string, begin, "\"");
	}

	public static String getSubstring(String string, String begin, String end) {
		String subString = "";
		int beginIndex = string.indexOf(begin);
		// 判断起始下标是否为空，不为空则重新赋值
		if (beginIndex == -1) {
			System.out.println("没有起始字符串！请检查！");
		} else {
			beginIndex += begin.length() + 1;
		}
		// 判断结束下标是否为空
		if (end == null) {
			subString = string.substring(beginIndex);
		} else {
			int endIndex = string.indexOf(end, beginIndex);
			if ("".equals(end) || endIndex == -1) {
				subString = string.substring(beginIndex);
			} else {
				subString = string.substring(beginIndex, endIndex);
			}
		}
		// int endIndex = string.indexOf(end, beginIndex);
		// if (endIndex == -1) {
		// subString = string.substring(beginIndex);
		// } else {
		// subString = string.substring(beginIndex, endIndex);
		// }
		return subString;
	}

	/**
	 * 根据后缀名判断该路径是否为绝对路径
	 * 
	 * @param path
	 * @param postfix
	 *            后缀名
	 * @return
	 */
	public static boolean theIsAbsolutePath(String path, String postfix) {
		boolean flag = false;
		if (path.indexOf("http") != -1 && path.indexOf(postfix) != -1) {
			flag = true;
		}
		return flag;
	}

	/**
	 * 新建文件夹，判断文件夹是否存在，不存在就新建
	 * 
	 * @param folderName
	 */
	public static void createFolder(String folderName) {
		File folder = new File(folderName);
		if (!folder.exists()) {
			folder.mkdirs();
		}
	}

	/**
	 * 新建文件，判断文件是否存在，不存在就新建
	 * 
	 * @param fileName
	 */
	public static File createFile(String fileName) {
		File file = new File(fileName);
		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return file;
	}

	/**
	 * 获取网页源码
	 * 
	 * @param url
	 * @return
	 */
	public static String getCodeByUrl(String url) {
		if (url.indexOf("http:") != -1) {
			homePage = "http://" + getSubstring(url, "http:/", "/") + "/";
		} else if (url.indexOf("https:") != -1) {
			homePage = "https://" + getSubstring(url, "https:/", "/") + "/";
		}
		System.out.println("本网站的主页是：" + homePage);
		StringBuilder input;
		try {
			// openStream()返回的是openConnection().getInputStream();
			// 所以不用url.openConnection
			InputStreamReader in = new InputStreamReader(new URL(url).openStream());
			input = new StringBuilder();
			// 将流中的字符加到StringBuilder中
			while ((ch = in.read()) != -1) {
				input.append((char) ch);
			}
			// 转码
			code = new String(input.toString().getBytes("UTF-8"));
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return code;
	}

}
